//
//  TravelViewController.m
//  chanyou
//
//  Created by wanli on 15/1/2.
//  Copyright (c) 2015年 wanli. All rights reserved.
//--------------------- 旅行地  ----------------------

#import "TravelViewController.h"
#import "ConnectModel.h"
#import "UIImageView+WebCache.h"
#import "TravelTableViewCell.h"
#import "AttractionsViewController.h"
#import "MJRefresh.h"
#import "MJRefreshHeaderView.h"
#import "MJRefreshFooterView.h"
#import "SDImageCache.h"
@interface TravelViewController ()

@end

@implementation TravelViewController

- (void)dealloc
{
    [_destination_id release];
    [_tableArray release];
    [_tableView release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tableArray = [NSMutableArray array];
        self.count = 1;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
//    NSLog(@"id = %@", _destination_id);
    [self creatTableView];
//    [self startConnect];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-back.png"] style:UIBarButtonItemStyleDone target:self action:@selector(backAction)]autorelease];
    // navigation的title
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 45, 100)];
    label.textColor = [UIColor colorWithRed:255 / 255.0 green:69 / 255.0 blue:0 alpha:1];
    label.font = [UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:20];
    label.text = @"旅行地";
    self.navigationItem.titleView = label;

    // Do any additional setup after loading the view.
}

- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
    
    //    [[SDImageCache sharedImageCache] clearMemory];
}

- (void)backAction:(id)sender{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)creatTableView{
    self.tableView = [[[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain]autorelease];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerClass:[TravelTableViewCell class] forCellReuseIdentifier:@"travleCell"];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];

    [self refresh];
}
- (void)refresh
{
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView headerBeginRefreshing];
    self.tableView.headerReleaseToRefreshText = @"刷新喽";
    self.tableView.headerRefreshingText = @"刷新";
    
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    self.tableView.footerRefreshingText = @"加载";
    
}
- (void)headerRereshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [_tableArray removeAllObjects];
        NSString *url = [NSString stringWithFormat:@"%@%@.json?page=1", @"http://chanyouji.com/api/destinations/attractions/", _destination_id];
        [self startConnect:url];
        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        
    });
}

- (void)footerRereshing
{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        self.count++;
        NSString *strCount = [NSString stringWithFormat:@"page=%d", self.count];
        
        
            NSString *str = [NSString stringWithFormat:@"%@%@.json?page=1", @"http://chanyouji.com/api/destinations/attractions/", _destination_id];
            NSString *url = [str stringByReplacingOccurrencesOfString:@"page=1" withString:strCount];
            [self startConnect:url];
            [self.tableView reloadData];
            [self.tableView footerEndRefreshing];
        
    });
}



- (void)startConnect:(NSString *)url{
    
    
    __block TravelViewController *travel = self;
    [ConnectModel connectModelWithUrl:url parmaters:nil finished:^(NSData *data) {
        NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        [travel.tableArray addObjectsFromArray:array];
        [travel.tableView reloadData];
    }];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_tableArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TravelTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"travleCell"];
    NSDictionary *dic = [_tableArray objectAtIndex:indexPath.row];
    NSString *imagePath = [dic objectForKey:@"image_url"];
//    [cell.image_urlView imageWithUrl:imagePath placeHolder:nil];
    [cell.image_urlView sd_setImageWithURL:[NSURL URLWithString:imagePath] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
    
    cell.attraction_trips_count.text = [NSString stringWithFormat:@"%@ %@", [dic objectForKey:@"attraction_trips_count"], @"篇游记"];
    cell.name.text = [dic objectForKey:@"name"];
  
    cell.descrip.text = [dic objectForKey:@"description"];
    
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    AttractionsViewController *att = [[AttractionsViewController alloc] init];
    NSDictionary *dic = [_tableArray objectAtIndex:indexPath.row];
    att.destination_id = [NSString stringWithFormat:@"%@", [dic objectForKey:@"id"]];
    
//    [self presentViewController:att animated:YES completion:nil];
    [self.navigationController pushViewController:att animated:YES];
        [[SDImageCache sharedImageCache] clearMemory];
    [att release];
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.view.frame.size.height / 6;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
